﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSLib.CodeFormating.Adapters;
using PSLib.CodeFormating.Lexems;
using PSLib.CodeFormating.Formatters;

namespace PSLib.CodeFormating
{
	public static class Formatter
	{
		public static string Format(string source, Adapters.LanguageAdapter adapter, Formatters.FormatConfiguration settings)
		{
			LexemList list = LexemParser.Parse(source, adapter,true);
			adapter.PostProcessLexemList(list);

			foreach (var item in list)
			{
				if (settings.LexemConfigurationCollection.Contains(item.Type))
				{
					LexemConfiguration lexemSetting = settings.LexemConfigurationCollection[item.Type];
					if (lexemSetting.ReplacementCollection.ContainsKey(string.Empty))
						item.LexemSource = lexemSetting.ReplacementCollection[string.Empty];
					else
					{
						string newLexem = string.Empty;
						foreach (var symbol in item.LexemSource)
						{
							string symbolString = string.Empty;
							symbolString += symbol;
							if (lexemSetting.ReplacementCollection.ContainsKey(symbolString))
							{
								newLexem += lexemSetting.ReplacementCollection[symbolString];
							}
							else
							{
								newLexem += symbolString;
							}
						}
						item.LexemSource = newLexem;
					}
				}
			}
			LexemList listOptimized = LexemParser.Optimize(list,true);

			string result = string.Empty;
			result += settings.Prefix;
			foreach (var item in listOptimized)
			{
				if (settings.LexemConfigurationCollection.Contains(item.Type))
				{
					LexemConfiguration lexemSetting = settings.LexemConfigurationCollection[item.Type];
					string lexemSource = item.LexemSource;
					result += lexemSetting.Prefix + lexemSource + lexemSetting.Postfix;
				}
				else result += item.LexemSource;
			}

			result += settings.Postfix;

			return result;
		}
	}
}
